package com.dodayum.controller;


import com.dodayum.service.FoundExcelService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.nio.file.Files;

@RestController
@RequestMapping("/downloadFile")
public class DownloadFileController {

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam String filename,
                                               @RequestHeader(value = "Range", required = false) String rangeHeader) throws IOException {
        String FILE_DIRECTORY = "/Users/dodayum/Downloads/demoFile/";
        File file = new File(FILE_DIRECTORY + filename);
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        long fileLength = file.length();
        byte[] data;
        long start = 0, end = fileLength - 1;

        if (StringUtils.hasText(rangeHeader)) {
            String[] ranges = rangeHeader.replace("bytes=", "").split("-");
            try {
                start = ranges.length > 0 && !ranges[0].isEmpty() ? Long.parseLong(ranges[0]) : start;
                end = ranges.length > 1 && !ranges[1].isEmpty() ? Long.parseLong(ranges[1]) : end;
            } catch (NumberFormatException e) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
        }

        if (start > end || start >= fileLength) {
            return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
                    .header(HttpHeaders.CONTENT_RANGE, "bytes */" + fileLength)
                    .body(null);
        }

        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
            randomAccessFile.seek(start);
            int length = (int) (end - start + 1);
            data = new byte[length];
            randomAccessFile.readFully(data);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(file.toPath()));
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        headers.add(HttpHeaders.ACCEPT_RANGES, "bytes");
        headers.add(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileLength);

        return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT).headers(headers).body(data);
    }

    @Resource
    private FoundExcelService foundExcelService;

    @GetMapping("/found")
    public void found(HttpServletResponse response) throws Exception {
// 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 中文文件名需要进行 URLEncoder 处理
        String fileName = URLEncoder.encode("多Sheet导出文件", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 的 WriteWorkbook 创建一个工作簿
        try (ServletOutputStream out = response.getOutputStream()) {
            foundExcelService.foundExcel(out);
        } catch (Exception e) {
            // 重置响应
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

}
